package com.googlecode.connectlet.crypto.cipher.jce;

import java.io.IOException;
import java.io.ObjectInputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.googlecode.connectlet.crypto.cipher.Decipheror;

public class JceDecipheror implements Decipheror {
	private static final long serialVersionUID = 1L;

	private transient Cipher cipher;
	private transient int blockSize;

	private String algorithm;
	private byte[] key;

	public JceDecipheror(String algorithm, byte[] key) {
		this.algorithm = algorithm;
		this.key = key;
		init();
	}

	@Override
	public int getBlockSize() {
		return blockSize;
	}

	@Override
	public void decrypt(byte[] src, int srcPos, byte[] dest, int destPos) {
		try {
			cipher.doFinal(src, srcPos, blockSize, dest, destPos);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private void init() {
		try {
			cipher = Cipher.getInstance(algorithm + "/ECB/NoPadding");
			cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, algorithm));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		blockSize = cipher.getBlockSize();
	}

	private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
		in.defaultReadObject();
		init();
	}
}